import React, { PureComponent } from 'react';
import { Icon, Input, message, Tag } from 'antd';

class OtherSpec extends PureComponent {
  state = {
    inputVisible: false,
    inputValue: '',
  };

  render() {
    const { inputVisible, inputValue } = this.state;
    const { value, onChange, opeSpecId } = this.props;
    let specs = []
    if (value && value.values && value.values.length > 0) {
      specs = value.values
    }

    const saveInputRef = input => {
      this.input = input;
    };

    const showInput = () => {
      this.setState({ inputVisible: true }, () => this.input.focus());
    };

    const handleInputChange = e => {
      this.setState({ inputValue: e.target.value });
    };

    const handleInputAdd = () => {
      if (!inputValue) {
        this.setState({ inputVisible: false, inputValue: '' });
        return;
      }
      const index = specs.findIndex(f => f.name === inputValue);
      if (index === -1) {
        const newValue = { ...value };
        newValue.values.push({
          name: inputValue,
        });
        onChange(newValue, opeSpecId);
        this.setState({ inputVisible: false, inputValue: '' });
      } else {
        message.info('已存在相同的规格');
      }
    };

    const handleTagClose = index => {
      const newValue = { ...value };
      newValue.values.splice(index, 1);
      onChange(newValue, opeSpecId);
    };

    return (
      <div>
        {specs.map((tag, index) => {
          return (
            <Tag color="geekblue" key={tag.name} closable onClose={() => handleTagClose(index)}>
              {tag.name}
            </Tag>
          )
        })}
        {inputVisible && (
          <Input
            ref={saveInputRef}
            type="text"
            size="small"
            style={{ width: 78 }}
            value={inputValue}
            onChange={handleInputChange}
            onBlur={handleInputAdd}
            onPressEnter={handleInputAdd}
          />
        )}
        {!inputVisible && (
          <Tag
            color="volcano"
            onClick={() => showInput()}
            style={{ background: '#fff', borderStyle: 'dashed' }}
          >
            <Icon type="plus"/> 新增
          </Tag>
        )}
      </div>
    );
  }
}

export default OtherSpec;
